#include <iostream>
#include <string>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

class UdpServer
{
private:
    int _sockfd;
    std::string _ip; // "0"
    uint16_t _port;

public:
    UdpServer(uint16_t port)
        : _port(port), _ip("0")
    {
        // 创建套接字
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            std::cout << "创建套接字失败" << std::endl;
            exit(1);
        }
        std::cout << "创建套接字成功" << std::endl;

        // 绑定端口和ip
        sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            std::cout << "绑定端口和ip失败" << std::endl;
            exit(1);
        }
        std::cout << "绑定端口和ip成功" << std::endl;
    }

    void Start()
    {
        struct sockaddr_in client_addr;
        socklen_t len = sizeof(client_addr);
        while (true) // 先接收消息，然后发送消息
        {
            //char recv_message[1024] = {0};
            char *recv_message = new char[1024];
            //sizeof(recv_message),recv_message是指针，sizeof指针在64为下是8字节，8-1为7
            int res_recv = recvfrom(_sockfd, recv_message, 1024 - 1, 0, (struct sockaddr *)&client_addr, &len);
            if (res_recv == -1)
            {
                std::cout << "接收失败" << std::endl;
                exit(errno);
            }
            std::cout << "res_recv: " << res_recv << std::endl;
            recv_message[res_recv] = 0;
            std::cout << "接收成功: " << recv_message << std::endl;

            int res_send = sendto(_sockfd, recv_message, sizeof(recv_message), 0, (struct sockaddr *)&client_addr, len);
            if (res_send == -1)
            {
                std::cout << "发送失败" << std::endl;
                exit(errno);
            }
            std::cout << "发送成功" << std::endl;
            delete[] recv_message;
        }
    }
};